package com.szgd.service.sys;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.szgd.dao.ecdata.sys.DeptMapper;
import com.szgd.util.CsvUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.WebServiceUtil;


@Service
public class DeptService {
	@Autowired
	private DeptMapper deptMapper;
	private static Logger logger = Logger.getLogger(DeptService.class);
	
	public static final String method = "queryDeptList";// 调用方法名

	public List<Map<String,String>> getFirstLevelDept(Map<String, Object> params){
		return deptMapper.getFirstLevelDept(params);
	}

	/**获取二级部门，某支队下的所有中队
	 *
	 * @param params
	 * @return
	 */
	public List<Map<String,String>> getSecondLevelDept(Map<String, Object> params){
		return deptMapper.getSecondLevelDept(params);
	}

	public List<String> getFirstLevelByDept(){
		return deptMapper.getFirstLevelByDept();
	}


	/*
	 * 调用十所提供的WS路径，获取全部最新的内网部门信息，更新部门表
	 */
	public String deptInfoUpdate2(String synpath){
		try{
			String serviceAddres = PropertiesUtil.getPropValue("/ws.properties", "mhws");
			String deptXML = (String) WebServiceUtil.callWs(serviceAddres, method, null);
			return insertIntoCsv2(deptXML,synpath);
		}catch(Exception e){
			return "-1";
		}
	    
	}
	/**
	 * 解析XML字符串并插入CSV文件
	 * 样式：
	 *  <Dept>
     *     <deptId>142</deptId>
     *     <deptCd>SHJC17K00Z00</deptCd>
     *     <deptName>市局领导</deptName>
     *     <deptShortName>市局领导</deptShortName>
     *     <sortNumber>101190000</sortNumber>
     *     <deptParentId>2</deptParentId>
     *     <address> </address>
     *     <postAlCode> </postAlCode>
     *     <operateStatus>1</operateStatus>
     *     <pubFlag>0</pubFlag>
     *     <remarkNumber>0</remarkNumber>
     *     <cityCode>021</cityCode>
     *   </Dept>
	 * @param deptXML
	 */
	public String insertIntoCsv2(String deptXML,String synpath){
		String[] headTitle = {"部门Id号（唯一）","机构代码","机构名称","机构简称","机构排序号","父机构ID","通讯地址",
				     "邮政编码","操作状态","发布标志(0：未发布1:已发布)","预留字段","城市编码"};
		String[] childrenAttribute = {"deptId","deptCd","deptName","deptShortName","sortNumber","deptParentId",
				     "address","postAlCode","operateStatus","pubFlag","remarkNumber","cityCode"};
		try {
			if(null!=deptXML && !"".equals(deptXML) && deptXML.length()>0){
				DateFormat dateTimeFormat=new SimpleDateFormat("yyyyMMddHHmmss");
				File targetFilePath = new File(synpath);
				if(!targetFilePath.exists())
					targetFilePath.mkdirs();
				
				String csvFilePath = synpath + "/dept"+dateTimeFormat.format(new Date())+".csv";;
				File targetFile = new File(csvFilePath);
				if(!targetFile.exists())
					targetFile.createNewFile();
				
				CsvUtil.createCSVHead(headTitle, targetFile);	//取消改行的注釋，啟用代碼 Modified by Jiayb at 2017-4-27 10:06:46
				CsvUtil.appendCsvContent(deptXML, "Dept", childrenAttribute, targetFile);
				return csvFilePath;
			}
		} catch (IOException e) {
			logger.error("解析并插入更新的用户信息到CSV文件异常！",e);
		}
		return "-1";
	}
	
	
	/*
	 * 同步部门数据 author by 00
	 */
	public boolean synchro(){
		boolean result = false;
		System.out.println("开始同步部门数据!");
		//获得CSV文件路径
		//String syn_pathdept="C:/dataUpdate/dept20170501010211.csv";
		String syn_pathdept = "";
		//部署在服務器使用
		String syn_path = PropertiesUtil.getPropValue("/ws.properties","syn_path");
		System.out.println("syn_path1="+syn_path);
		syn_pathdept=deptInfoUpdate2(syn_path);
		System.out.println("syn_path2="+syn_pathdept);
		if(syn_pathdept.equals("-1")){
			System.out.println("创建csv文件失败，中断执行");
		}
		File targetFile2 = new File(syn_pathdept);
		//將參數1修改為2  Modified by Jiayb at 2017-4-27
		String flag=CsvUtil.parseCSVFile3A(targetFile2,"GBK",2);
		if(flag.equals("1")){
			String deptflag=batchInsertDeptAfter();
			if("1".equals(deptflag)){
				System.out.println("同步部门数据成功!");
				result = true;
			}
		}
		return result;
	}


	/**
	 * 获得部门列表
	 * @param params map结构，可选择传递dept_cd参数与否
	 * @return
	 */
	public List<Map<String,Object>> getDeptListRecord(Map<String, Object> params){
		return deptMapper.getDeptListRecord(params);
	}
	
	/**
	 * 查询部门所有信息，提供给ztree以树形结构展示
	 * 注意：
	 * 采用ztree的simpleData
	 * 返回所有部门信息list，指定每条记录的rootPId、idKey、pIdKey三元素（即树结构的根节点、ID、父ID三个参数）
	 * ztree自动构建树形结构（不需要通过程序处理的方式返回组织数据，ztree在内存中重构tree模型，生成根节点以及非父节点的children）
	 * @param params
	 * @return
	 */
	public List<Map<String,Object>> getAllDeptInfo(Map<String, Object> params){
		List<Map<String,Object>> obj = deptMapper.getAllDeptInfo(params); 
		return obj;
	}

	public List<Map<String,Object>> getAllChildById(String id ){
		List<Map<String,Object>> obj = deptMapper.getAllChildById(id);
		return obj;
	}

	public void batchInsertDept(List<Map<String,Object>> params){
		deptMapper.deleteTempDept("");
		deptMapper.batchInsertDept(params);
	}
	public String batchInsertDeptAfter(){
		try{
		deptMapper.insertNewDept("");
		deptMapper.updateAllDept("");
		deptMapper.updateDelDept("");
		return "1";
		}catch(Exception e){
			return "0";
		}
	}
	
	/**
	 * 根据ROLE_ID，查询所有未分配到该角色下的用户列表（包含组织机构）
	 * @param params
	 * @return
	 */
	public List<Map<String,Object>> getNoGrantUsers(Map<String, Object> params){
		return deptMapper.getNoGrantUsers(params);
	}
	public List<Map<String,Object>> getOwenDeptUsers(Map<String, Object> params){
		return deptMapper.getOwenDeptUsers(params);
	}
	
	public Map<String,Object> getParentDept(String deptCD){
		List<Map<String,Object>> deptList = deptMapper.getParentDept(deptCD);
		if(deptList == null ){
			return null;
		}
		return deptList.get(0);
	}
	
	public Integer getZhiDui_deptId(String dept_cd){
		return deptMapper.getZhiDui_deptId(dept_cd);
	}
	
	public String getParentDeptName(String deptCD){
		return deptMapper.getParentDeptName(deptCD);
	}

	public 	List<Map<String,String>> getDeptCDByName(Map<String, Object> params)
	{
		return  deptMapper.getDeptCDByName(params);
	}
	
	public Integer getNewDeptId(){
		return deptMapper.getNewDeptId();
	}
	
	public Integer getNewSort(){
		return deptMapper.getNewSort();
	}
	
	public int insertDept(Map<String, Object> params) throws Exception{
		return deptMapper.insertDept(params);
	}
	public int updateDept(Map<String, Object> params) throws Exception{
		return deptMapper.updateDept(params);
	}
}
